import * as echarts from "../../components/ec-canvas/echarts"
import ble from "../../utils/bluetooth"
var option = {},
    chart,
    xTime = [],
    data = [
        [],
        [],
        [],
        [],
        []
    ],
    echartsData = [
        [],
        [],
        [],
        [],
        []
    ],
    time = 0,
    color = ['#de86e6', '#e93225', '#64ad75', '#0100f2', '#fdff54']

function initChart(canvas, width, height, dpr) {
    chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);
    // chart.setOption(option);
    // return chart;
}
Page({
    data: {
        ec: {
            onInit: initChart
        },
        startTime: '00:00',
        endTime: '00:00',
        color,
        time,
        writeDeviceId: '',
        writeServiceId: '',
        writeCharacteristicId: '',
        index: 0,
        dayArr: ['00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:00', '05:30', '06:00', '06:30', '07:00', '07:30', '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30'],
    },
    onLoad: function () {
        xTime = []
        for (let i = 0; i < 24; i++) {
            xTime.push(i)
        }
        this.reset()
    },
    onReady: function () {
        this.setoption()
    },
    sliderchange(e) {
        let index = e.currentTarget.dataset.index
        let value = e.detail.value
        this.setData({
            [`data[${index}][${time}]`]: value
        })
        if (time % 2 == 0) {
            this.setData({
                [`echartsData[${index}][${time / 2}]`]: value
            })
        }
        this.setoption()
    },
    operation(e) {
        e = e.currentTarget.dataset.i
        if ((e > 0 && time < 47) || (e < 0 && time > 0)) {
            time += e
        } else if (e < 0 && time == 0) {
            time = 47
        } else {
            time = 0
        }
        this.setData({
            time
        })
    },
    operation2(e) {
        let i = e.currentTarget.dataset.i
        let index = e.currentTarget.dataset.index
        let num = this.data.data[index][time]
        console.log('data', this.data.data)
        if ((i > 0 && num < 100) || (i < 0 && num > 0)) {
            num += i
        } else if ((i < 0 && num == 0) || (i > 0 && num == 100)) {
            return
        }
        this.setData({
            [`data[${index}][${time}]`]: num
        })

        if (time % 2 == 0) {
            this.setData({
                [`echartsData[${index}][${time / 2}]`]: num
            })
        }
        this.setoption()
    },
    bindPickerdateChange: function (e) {
        this.setData({
            index: e.detail.value,
            time: e.detail.value
        })
        time = e.detail.value
    },
    bindStartTimeChange: function (e) {
        this.setData({
            startTime: e.detail.value
        })
    },
    bindEndTimeChange: function (e) {
        this.setData({
            endTime: e.detail.value
        })
    },
    setoption() {
        option = {
            color,
            // legend: {
            //   data: ['a', 'b', 'c', 'd', 'e']
            // },
            grid: {
                left: '1%',
                right: '3%',
                bottom: '0',
                top: '5%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLabel: {
                    interval: 0,
                    textStyle: {
                        fontSize: '8'
                    },
                    formatter: (val) => {
                        return val
                    }
                },
                axisTick: {
                    show: false //坐标轴刻度线
                },
                data: xTime
            },
            yAxis: {
                show: true,
                type: 'value',
                max: 100,
                axisTick: {
                    show: false
                },
                axisLine: {
                    show: true,
                },
                axisLabel: {
                    show: true,
                    interval: 20,
                    formatter: '{value}%',
                    textStyle: {
                        fontSize: '8'
                    }
                },
                // splitLine: {
                //   show: true
                // }
            },
            series: [{
                    name: 'a',
                    type: 'line',
                    smooth: true,
                    data: echartsData[0],
                },
                {
                    name: 'b',
                    type: 'line',
                    smooth: true,
                    data: echartsData[1]
                },
                {
                    name: 'c',
                    type: 'line',
                    smooth: true,
                    data: echartsData[2]
                },
                {
                    name: 'd',
                    type: 'line',
                    smooth: true,
                    data: echartsData[3]
                },
                {
                    name: 'e',
                    type: 'line',
                    smooth: true,
                    data: echartsData[4]
                }
            ]
        };
        setTimeout(function () {
            chart.setOption(option);
        }, 500)
    },
    // 读取低功耗蓝牙设备的特征值的二进制数据值
    async readValue() {
        ble.getBLEDeviceServices()
        // if (!res.ok) {
        //   wx.showModal({
        //     title: `错误代码${res.errCode}`,
        //     content: res.errMsg,
        //     showCancel: false,
        //     confirmText: '好的'
        //   })
        //   console.log(res)
        // }
    },
    // 写入字符串数据
    async writeString() {
        let indexs = 1
        let allDatas = []
        this.data.data.forEach(function (item, index) {
            var result = [];
            for (var i = 0, len = item.length; i < len; i += 16) {
                result.push(item.slice(i, i + 16));
            }
            result.forEach(function (item, index) {
                let data = ['0x54', '0x4D', '0x52']
                data.push(indexs)
                var allData = data.concat(item);
                for (let i = 3, len = allData.length; i < len; i++) {
                    allData[i] = '0x' + formatNumber(allData[i].toString(16))
                }
                allDatas[indexs - 1] = allData
                indexs++
            })
        })
        console.log("15个数据包", allDatas);
        allDatas.forEach(async function (item, index) {
            let res = await ble.writePrescriptiveDirective(item)
            sleep(0.02)
        })
        sleep(0.1)
        await this.modeToAuto()
    },
    // 将模式切换到自动模式
    async modeToAuto() {
        let data = ['0x4d', '0x4f', '0x44', '0x01']
        let res = await ble.writePrescriptiveDirective(data)
        console.log("切换自动模式", res);
        return res
    },
    // 写入规定指令
    async writePrescriptiveDirective() {
        let res = await ble.writePrescriptiveDirective()
        console.log('写入数据的结果：', res)
    },
    // 定时开关开关
    async switchChange(e) {
        if (e.detail.value) {
            if (this.data.startTime == this.data.endTime) {
                this.setData({
                    checked: false
                })
                wx.showToast({
                    title: '起始时间重合',
                    icon: 'error'
                })
                return
            }
            this.setData({
                checked: true
            })
            let tmtData = ['0x54', '0x4D', '0x54', '0x01']
            tmtData.push(parseInt(this.data.startTime.split(':')[0]), parseInt(this.data.startTime.split(':')[1]))
            tmtData.push(parseInt(this.data.endTime.split(':')[0]), parseInt(this.data.endTime.split(':')[1]))
            for (let i = 4, len = tmtData.length; i < len; i++) {
                tmtData[i] = '0x' + formatNumber(tmtData[i].toString(16))
            }
            let res = await ble.writePrescriptiveDirective(tmtData)
            console.log('定时开关（开）', res)
        } else {
            this.setData({
                checked: false,
            })
            let tmtData = ['0x54', '0x4D', '0x54', '0x00']
            let res = await ble.writePrescriptiveDirective(tmtData)
            console.log('定时开关（关）', res)
        }
    },
    // 重置
    reset() {
        data = [
            [],
            [],
            [],
            [],
            []
        ]
        echartsData = [
            [],
            [],
            [],
            [],
            []
        ]
        time = 0
        for (let i = 0; i < 48; i++) {
            data[0].push(0)
            data[1].push(0)
            data[2].push(0)
            data[3].push(0)
            data[4].push(0)
            echartsData[0].push(0)
            echartsData[1].push(0)
            echartsData[2].push(0)
            echartsData[3].push(0)
            echartsData[4].push(0)
        }
        this.setData({
            data,
            time,
            echartsData
        })
        this.setoption()
    }
})

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function sleep(delay) {
    var start = (new Date()).getTime();
    while ((new Date()).getTime() - start < delay) {
        continue;
    }
}